#include "BreakPointService.h"
#include <iostream>
#include "BreakPointMem.h"
#include "BreakPointFile.h"


BreakPointService::BreakPointService()
:status(0)
, mem(new BreakPointMem)
, file(new BreakPointFile("./seqNo.bin"))
{
}
BreakPointService::~BreakPointService()
{
    if(file){
        delete file;
    }
    if(mem){
        delete mem;
    }
}

void BreakPointService::start(){
    std::cout << "BreakPointService::start " << std::endl;

    std::cout << "BreakPointService::loadFromFile " << std::endl;
    long long seqNo = file->get();
    mem->set(seqNo);

}
void BreakPointService::stop(){
    long long seqNo = mem->get();
    std::cout << "BreakPointService::saveToFile " << std::endl;
    file->set(seqNo);

    std::cout << "BreakPointService::stop to: " << seqNo << std::endl;
}

void BreakPointService::connected(){
    std::cout << "BreakPointService::connected " << std::endl;
    if(status == INITED){
        status = CONNECTED;
    }
    else{
        std::cout << "current status error:"
            << "\n\tstatus :"  << status << " [0-inited,1-connected,2-disconnected,3-logined]" 
            << std::endl;
    }

    sendMessage("login-req");
}
void BreakPointService::receivedNormalResp(const char * msg){
    std::cout << "BreakPointService::receive :[" << msg << "]" << std::endl;
    mem->set(mem->get() + 1);//fake action
}
void BreakPointService::timeout(){
    std::cout << "BreakPointService::timeout "
        <<"-> query the data [" <<  mem->get()+1 <<  ", MAX)" << std::endl;

    sendMessage("breakpoint-req");

    std::cout << "BreakPointService::saveToFile " << std::endl;
    file->set(mem->get());
}








void BreakPointService::disconnected(){
    if(status == CONNECTED || status == LOGINED){
        status = DISCONNECTED;
    }
    else{
        std::cout << "current status error:"
            << "\n\tstatus :"  << status << " [0-inited,1-connected,2-disconnected,3-logined]" 
            << std::endl;
    }
    std::cout << "BreakPointService::disconnected " 
        << "\n\tstatus :"  << status << " [0-inited,1-connected,2-disconnected,3-logined]" 
        << std::endl;
}


void BreakPointService::receivedLoginResp(const char * msg){
    std::cout << "BreakPointService::receive :[" << msg << "]" 
        << "\n\tswitch to [login] status if response ok" 
        << std::endl;

    if(status == CONNECTED){
        status = LOGINED;
    } 
    else{
        std::cout << "current status error:" 
            << "\n\tstatus :"  << status << " [0-inited,1-connected,2-disconnected,3-logined]" 
            << std::endl;
    }
}

void BreakPointService::receivedBreakPointResp(const char * msg){
    std::cout << "BreakPointService::receive :[" << msg << "]" << std::endl;
}

void BreakPointService::sendMessage(const char * msg){
    std::cout << "BreakPointService::send : [" << msg << "] " 
        << "\n\tstatus :"  << status << " [0-inited,1-connected,2-disconnected,3-logined]" 
        << std::endl;
}
